package com.sh.apigateway.filter;

import com.sh.apicommon.common.ResultUtils;
import com.sh.apicommon.entity.InterfaceInfo;
import com.sh.apicommon.entity.User;
import com.sh.apicommon.service.ApiBackendService;
import com.sh.apicommon.utils.SignUtils;
import com.sh.apigateway.service.InvokeCountToJms;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class InterfaceInvokeFilter implements GatewayFilter, Ordered {

    private static final String INTERFACE_HOST = "http://localhost:8123";   // 接口地址

    @DubboReference
    private ApiBackendService apiBackendService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private InvokeCountToJms invokeCountToJms;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.打上请求日志
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = INTERFACE_HOST + request.getPath().value();   // 请求路径
        String method = request.getMethod().toString();    // 请求方法
        recordRequestLogs(request);   // 记录请求日志
        //3.用户鉴权(API签名认证)
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");   // 获取请求头中的accessKey
        String body = headers.getFirst("body");
        String sign = headers.getFirst("sign");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        // 校验用户
        User invokeUser = null;
        try {
            invokeUser = apiBackendService.getInvokeUser(accessKey);
        } catch (Exception e) {
            log.error("远程调用获取调用接口用户的信息失败");
            e.printStackTrace();
        }
        if (invokeUser == null) {
            return handleNoAuth(response);
        }
        // 校验签名
        String secretKey = invokeUser.getSecretKey();
        String serverSign = SignUtils.getSign(body, secretKey);
        if (sign == null || !sign.equals(serverSign)) {
            log.error("签名校验失败!!!!");
            return handleNoAuth(response);
        }
        // 防止重放   添加成功就是5秒内操作过
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(nonce, "1", 5, TimeUnit.SECONDS);
        if (success == null || !success) {
            log.error("随机数存储失败!!!!");
            return handleNoAuth(response);
        }
        // 通过时间戳防止重放
        if (timestamp != null) {
            long sendTime = Long.parseLong(timestamp);
            long nowTime = System.currentTimeMillis()/1000;
            if (Math.abs(nowTime - sendTime) > 5000) {
                log.error("时间戳过期或无效");
                return handleNoAuth(response); // 必须拦截！
            }
        } else {
            log.error("缺少时间戳");
            return handleNoAuth(response);
        }

        //4.远程调用判断接口是否存在以及获取调用接口信息
        InterfaceInfo interFaceInfo = null;
        try {
            interFaceInfo = apiBackendService.getInterFaceInfo(path, method);
        } catch (Exception e) {
            log.info("远程调用获取被调用接口信息失败");
            e.printStackTrace();
        }
        if (interFaceInfo == null || interFaceInfo.getStatus() != 1) {
            log.error("接口不存在 或者接口状态为不开放");
            return handleNoAuth(response);
        }
        //5.消息队列里面去
        invokeCountToJms.send(invokeUser.getId(), interFaceInfo.getId());

        //6.发起接口调用，网关路由实现
//        Mono<Void> filter = chain.filter(exchange);
        return handleResponse(exchange, chain, interFaceInfo.getId(), invokeUser.getId());
    }

    /**
     * 响应之后的操作
     *
     * @param exchange
     * @param chain
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    private Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            //缓存数据
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            //响应状态码
            HttpStatus statusCode = (HttpStatus) originalResponse.getStatusCode();

            if (statusCode == HttpStatus.OK) {
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                //7.获取响应结果，打上响应日志
                                // 构建日志
                                log.info("接口调用响应状态码：" + originalResponse.getStatusCode());
                                //responseBody
                                String responseBody = new String(content, StandardCharsets.UTF_8);

//                                if (!(originalResponse.getStatusCode() == HttpStatus.OK)){
//                                    log.error("接口异常调用-响应体:" + responseBody);
//                                    // todo 消息回滚
//                                }

                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        } catch (Exception e) {
            log.error("gateway log exception.\n" + e);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -1; // 设置较高的优先级，确保在其他过滤器之前执行
    }

    public void recordRequestLogs(ServerHttpRequest request) {
        log.info("请求唯一标识 ===" + request.getId());
        log.info("请求路径 ===" + request.getURI().getPath());
        log.info("请求方法 ===" + request.getMethod());
        log.info("请求参数 ===" + request.getQueryParams());
        log.info("请求头 ===" + request.getHeaders());
        log.info("请求体 ===" + request.getBody());
        log.info("请求ip地址 ===" + request.getLocalAddress().getHostString());
        log.info("请求来源地址 ===" + request.getRemoteAddress().toString());   // 获取请求ip地址包括端口  /127.0.0.1:61238
    }


    // 设置响应状态码401
    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}